﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.NetworkRemoteDevice;
using Domain.NetworkService;
using System.Net;
using Domain.NetworkService.Behaviors.Interfaces;
using Domain.Entities;
using System.Web.Routing;
using System.ComponentModel.DataAnnotations;

namespace Web.Controllers
{
    public class ManageController : Controller
    {
        //
        // GET: /Manage/
        DBWorker dbWorker = new DBWorker();
        public ActionResult Manage()
        {
            ViewBag.Names = RemoteDeviceManager.GetNamesOfRemoteDevices();
            return View();
        }
        public ActionResult StartAllTests()
        {
            int x = RemoteDeviceManager.StartAllTests();
            dbWorker.WriteLog(String.Format("Запущено {0} служб", x), MessageType.Success);
            return RedirectToAction("Manage", "Manage");
        }
        public ActionResult StartAllTestsOfRemoteDevice(string devName, string daysAgo = "0.2")
        {
            OperationStatus s = RemoteDeviceManager.StartAllTestsOfRemoteDevice(devName);
            if (s == OperationStatus.Success)
            {
                dbWorker.WriteLog(String.Format("Службы устройства {0} перезаупещены успешно.", devName), MessageType.Success);
            }
            else
            {
                dbWorker.WriteLog(String.Format("Службы устройства {0} перезапустить неудалось: {1}", devName, s.ToString()), MessageType.Error);
            }
           return RedirectToAction("SurveyDetailed", "Survey", new { devName = devName, daysAgo = daysAgo });
        }
        public ActionResult StopAllTests()
        {
            int x = RemoteDeviceManager.StopAllTests();
            dbWorker.WriteLog(String.Format("Остановлено {0} служб", x), MessageType.Success);
            return RedirectToAction("Manage", "Manage");
        }
        [HttpPost]
        public ActionResult SaveState(string fileName)
        {
            OperationStatus opst = RemoteDeviceManager.SaveState(fileName);
            if (opst == OperationStatus.SaveStateCompleted)
            {
                dbWorker.WriteLog(String.Format("Данные усшешно сохранены в \"{0}\".", fileName), MessageType.Success);
            }
            else
            {
                dbWorker.WriteLog(String.Format("Произошла ошибка. Данные не сохранены."), MessageType.Error);
            }
            return RedirectToAction("Manage", "Manage");
        }
        [HttpPost]
        public ActionResult LoadState(string fileName)
        {
            OperationStatus opst = RemoteDeviceManager.LoadState(fileName);
            if (opst == OperationStatus.LoadStateSuccess)
            {
                dbWorker.WriteLog(String.Format("Данные из файла \"{0}\" успешно загружены.", fileName), MessageType.Success);
            }
            else
            {
                dbWorker.WriteLog(String.Format("Не удалось загрузить данные из файла \"{0}\".", fileName), MessageType.Error);
            }
            return RedirectToAction("Manage", "Manage");
        }
        [HttpPost]
        public ActionResult AddRemoteDevice(string newDeviceName)
        {
            OperationStatus opst = RemoteDeviceManager.AddRemoteDevice(newDeviceName);
            if (opst == OperationStatus.Success)
            {
                dbWorker.WriteLog(String.Format("Устройство \"{0}\" успешно добавлено.", newDeviceName), MessageType.Success);
            }
            else if (opst == OperationStatus.DeviceAlreadyExists)
            {
                dbWorker.WriteLog(String.Format("Устройство c именем \"{0}\" уже существует.", newDeviceName), MessageType.Error);
            }
            return RedirectToAction("Manage", "Manage");
        }
        public ActionResult DeviceProperty(string devName)
        {
            ViewBag.devName = devName;
            return View();
        }
        public ActionResult RemoveRemoteDevice(string devName)
        {
            OperationStatus opst = RemoteDeviceManager.RemoveRemoteDevice(devName);
            if (opst == OperationStatus.Success)
            {
                dbWorker.WriteLog(String.Format("Устройство \"{0}\" удалено успешно.", devName), MessageType.Success);
            }
            else
            {
                dbWorker.WriteLog(String.Format("Устройство c именем \"{0}\" не существует. Возможно кто-то его уже удалил.", devName),
                                    MessageType.Error);
            }
            return RedirectToAction("Manage", "Manage");
        }
        [HttpPost]
        public ActionResult AddTestToRemoteDevice(string devName, IDescription desc)
        {
            desc.Timeout = TimeSpan.FromSeconds(Double.Parse(desc.Timeout.Days.ToString()));
            TestsSimpleFabric tsf = new TestsSimpleFabric();
            if (tsf.MakeTest(desc))
            {
                OperationStatus opst = RemoteDeviceManager.AddTestToRemoteDevice(devName, tsf.Test);
                if (opst == OperationStatus.Success)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" успешно добавлена к устройству \"{1}\".",
                                            desc.ToString(), devName), MessageType.Success);
                }
                else if (opst == OperationStatus.TestAlreadyExists)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" уже существует на устройстве \"{1}\".",
                                            desc.ToString(), devName), MessageType.Error);
                }
                else if (opst == OperationStatus.DeviceNotFound)
                {
                    dbWorker.WriteLog(String.Format("При попытке добавить службу \"{0}\" не обнаружено устройство \"{1}\".",
                                            desc.ToString(), devName), MessageType.Error);
                }
            }
            else
            {
                dbWorker.WriteLog(String.Format("При добавлении службы \"{0}\" на устройство \"{1}\" возникла непредвиденная ошибка.",
                    desc.ToString(), devName), MessageType.Error);
            }
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }

        public ActionResult AddEchoTest(string devName, EchoDescription desc)
        {
            AddTestToRemoteDevice(devName, desc);
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
            //return View("DeviceProperty", new { devName = devName });
        }
        public ActionResult AddTestNS(string devName, Description desc)
        {
            AddTestToRemoteDevice(devName, desc);
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }
        public ActionResult AddTestSnmp(string devName, Description desc, OidNames SpecialSnmp)
        {
            desc.Special = SpecialSnmp;
            AddTestToRemoteDevice(devName, desc);
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }
        public ActionResult AddTestTcp(string devName, Description desc, TcpPorts SpecialTcp)
        {
            desc.Special = SpecialTcp;
            AddTestToRemoteDevice(devName, desc);
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }
        public ActionResult RemoveTest(string devName, string testName)
        {
            IDescription iDesc = RemoteDeviceManager.GetIDescriptionByTestName(testName);
            if (iDesc != null)
            {
                OperationStatus opst = RemoteDeviceManager.RemoveTestFromRemoteDevice(devName, iDesc);
                if (opst == OperationStatus.Success)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" успешно удалена с устройства \"{1}\".",
                                            iDesc.ToString(), devName), MessageType.Success);
                }
                else if (opst == OperationStatus.TestNotFound)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" на устройстве \"{1}\" не найдена.",
                                            iDesc.ToString(), devName), MessageType.Error);
                }
                else if (opst == OperationStatus.DeviceNotFound)
                {
                    dbWorker.WriteLog(String.Format("При попытке удалить службу \"{0}\" не обнаружено устройство \"{1}\".",
                                           iDesc.ToString(), devName), MessageType.Error);
                }
            }
            else
            {
                dbWorker.WriteLog(String.Format("При удалении службы \"{0}\" с устройства \"{1}\" возникла непредвиденная ошибка.",
                   testName, devName), MessageType.Error);
            }
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }
        public ActionResult StopTest(string devName, string testName)
        {
            IDescription iDesc = RemoteDeviceManager.GetIDescriptionByTestName(testName);
            if (iDesc != null)
            {
                OperationStatus opst = RemoteDeviceManager.StopSomeTest(devName, iDesc);
                if (opst == OperationStatus.Success)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" на устройстве \"{1}\" остановлена успешно.", testName, devName), MessageType.Success);
                }
                else if (opst == OperationStatus.TestNotFound)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" на устройстве \"{1}\" ненайдена.", testName, devName), MessageType.Error);
                }
                else if (opst == OperationStatus.DeviceNotFound)
                {
                    dbWorker.WriteLog(String.Format("При попытке остановить службу \"{0}\" не обнаружено устройство \"{1}\".",
                                           iDesc.ToString(), devName), MessageType.Error);
                }
            }
            else
            {
                dbWorker.WriteLog(String.Format("При остановке службы \"{0}\" на устройстве \"{1}\" возникла непредвиденная ошибка.",
                   testName, devName), MessageType.Error);
            }
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }
        public ActionResult StartTest(string devName, string testName)
        {
            IDescription iDesc = RemoteDeviceManager.GetIDescriptionByTestName(testName);
            if (iDesc != null)
            {
                OperationStatus opst = RemoteDeviceManager.StartSomeTest(devName, iDesc);
                if (opst == OperationStatus.Success)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" на устройстве \"{1}\" успешно запущена.", testName, devName), MessageType.Success);
                }
                else if (opst == OperationStatus.TestNotFound)
                {
                    dbWorker.WriteLog(String.Format("Служба \"{0}\" на устройстве \"{1}\" ненайдена.", testName, devName), MessageType.Error);
                }
                else if (opst == OperationStatus.DeviceNotFound)
                {
                    dbWorker.WriteLog(String.Format("При попытке запустить службу \"{0}\" не обнаружено устройство \"{1}\".",
                                           iDesc.ToString(), devName), MessageType.Error);
                }
            }
            else
            {
                dbWorker.WriteLog(String.Format("При запуске службы \"{0}\" на устройстве \"{1}\" возникла непредвиденная ошибка.",
                   testName, devName), MessageType.Error);
            }
            return RedirectToAction("DeviceProperty", "Manage", new { devName = devName });
        }
    }
}
